import { useState, useEffect } from 'react'
import { useNavigate, Outlet, useLocation } from 'react-router-dom'
import type { CSSProperties } from 'react'

interface StyleProps {
  pageContainer: CSSProperties;
  header: CSSProperties;
  headerLeft: CSSProperties;
  headerRight: CSSProperties;
  mainContent: CSSProperties;
  sidebar: CSSProperties;
  content: CSSProperties;
  logo: CSSProperties;
  navItem: CSSProperties;
  activeNavItem: CSSProperties;
  userInfo: CSSProperties;
  logoutButton: CSSProperties;
  dashboardCard: CSSProperties;
  card: CSSProperties;
  cardHeader: CSSProperties;
  cardTitle: CSSProperties;
  cardValue: CSSProperties;
  quickAccessSection: CSSProperties;
  quickAccessGrid: CSSProperties;
  quickAccessItem: CSSProperties;
  quickAccessIcon: CSSProperties;
  quickAccessText: CSSProperties;
  footer: CSSProperties;
  recentActivity: CSSProperties;
  activityItem: CSSProperties;
  activityTitle: CSSProperties;
  activityContent: CSSProperties;
  activityTime: CSSProperties;
}

// 模拟数据
const mockStats = {
  totalInventory: 1520,
  pendingOrders: 28,
  lowStockItems: 15,
  monthlySales: 142800
}

const mockActivities = [
  { id: 1, title: '入库通知', content: '供应商A的订单#12345已完成入库', time: '10分钟前' },
  { id: 2, title: '库存警报', content: '产品SKU-789库存低于安全阈值', time: '30分钟前' },
  { id: 3, title: '出库完成', content: '订单#56789已完成拣货和包装', time: '2小时前' },
  { id: 4, title: '系统通知', content: '系统将于今晚22:00进行维护', time: '5小时前' }
]

// 导航菜单项
const navItems = [
  { id: 'dashboard', label: '仪表盘', active: true },
  { id: 'inventory', label: '用户管理', active: false },
  { id: 'inbound', label: '资费标准', active: false },
  { id: 'outbound', label: '身份校验管理', active: false },
  { id: 'reports', label: '单位管理', active: false },
  { id: 'ShowPendingShipmentWaybills', label: '待发货运单', active: false },
  { id: 'shipped-orders', label: '已发货运单', active: false },
  { id: 'product-management', label: '产品管理', active: false },
  { id: 'pending-inventory', label: '待盘点订单', active: false },
  { id: 'inventory-io', label: '库存出入库', active: false },
  { id: 'create-inbound', label: '创建入库单', active: false },
  { id: 'pending-orders', label: '待确认订单', active: false },
  { id: 'Box', label: '箱子型号管理', active: false },
  { id: 'OnlineBoxes', label: '在库箱子', active: false },
  { id: 'online-ordering', label: '在线下单', active: false },
  { id: 'warehouse-management', label: '仓库管理', active: false },
  { id: 'operation-logs', label: '操作日志', active: false }
]

// 快速访问项
const quickAccessItems = [
  { id: 'add-inventory', label: '新增库存', icon: '📦' },
  { id: 'create-order', label: '创建订单', icon: '📝' },
  { id: 'scan-code', label: '扫码操作', icon: '📱' },
  { id: 'view-reports', label: '查看报表', icon: '📊' }
]

const style: StyleProps = {
  pageContainer: {
    display: 'flex',
    flexDirection: 'column',
    minHeight: '100vh',
    backgroundColor: '#f5f7fa'
  },
  header: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: '0 20px',
    height: '64px',
    backgroundColor: '#fff',
    boxShadow: '0 2px 4px rgba(0,0,0,0.08)'
  },
  headerLeft: {
    display: 'flex',
    alignItems: 'center'
  },
  headerRight: {
    display: 'flex',
    alignItems: 'center',
    gap: '15px'
  },
  mainContent: {
    display: 'flex',
    flex: 1,
    height: 'calc(100vh - 64px)'
  },
  sidebar: {
    width: '220px',
    backgroundColor: '#fff',
    boxShadow: '1px 0 3px rgba(0,0,0,0.05)',
    padding: '20px 0',
    overflowY: 'auto'
  },
  content: {
    flex: 1,
    padding: '24px',
    overflowY: 'auto'
  },
  logo: {
    fontSize: '22px',
    fontWeight: '600',
    color: '#333'
  },
  navItem: {
    padding: '12px 20px',
    cursor: 'pointer',
    fontSize: '15px',
    color: '#666',
    transition: 'all 0.2s',
    borderLeft: '3px solid transparent',
    display: 'flex',
    alignItems: 'center',
    gap: '10px'
  },
  activeNavItem: {
    backgroundColor: '#f0f5ff',
    color: '#6366f1',
    borderLeft: '3px solid #6366f1'
  },
  userInfo: {
    fontSize: '14px',
    color: '#333',
    display: 'flex',
    alignItems: 'center',
    gap: '8px'
  },
  logoutButton: {
    padding: '6px 12px',
    backgroundColor: '#f3f4f6',
    border: 'none',
    borderRadius: '4px',
    color: '#666',
    cursor: 'pointer',
    fontSize: '14px',
    transition: 'all 0.2s'
  },
  dashboardCard: {
    display: 'grid',
    gridTemplateColumns: 'repeat(4, 1fr)',
    gap: '20px',
    marginBottom: '24px'
  },
  card: {
    backgroundColor: '#fff',
    borderRadius: '8px',
    boxShadow: '0 2px 8px rgba(0,0,0,0.05)',
    padding: '20px',
    transition: 'transform 0.2s, box-shadow 0.2s'
  },
  cardHeader: {
    marginBottom: '10px'
  },
  cardTitle: {
    fontSize: '14px',
    color: '#666',
    marginBottom: '4px'
  },
  cardValue: {
    fontSize: '24px',
    fontWeight: '600',
    color: '#333'
  },
  quickAccessSection: {
    backgroundColor: '#fff',
    borderRadius: '8px',
    boxShadow: '0 2px 8px rgba(0,0,0,0.05)',
    padding: '20px',
    marginBottom: '24px'
  },
  quickAccessGrid: {
    display: 'grid',
    gridTemplateColumns: 'repeat(4, 1fr)',
    gap: '15px',
    marginTop: '15px'
  },
  quickAccessItem: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    padding: '15px',
    borderRadius: '8px',
    backgroundColor: '#f9fafc',
    border: '1px solid #eee',
    cursor: 'pointer',
    transition: 'all 0.2s'
  },
  quickAccessIcon: {
    fontSize: '24px',
    marginBottom: '8px'
  },
  quickAccessText: {
    fontSize: '14px',
    color: '#555'
  },
  recentActivity: {
    backgroundColor: '#fff',
    borderRadius: '8px',
    boxShadow: '0 2px 8px rgba(0,0,0,0.05)',
    padding: '20px'
  },
  activityItem: {
    padding: '12px 0',
    borderBottom: '1px solid #eee',
    display: 'flex',
    flexDirection: 'column',
    gap: '5px'
  },
  activityTitle: {
    fontSize: '15px',
    fontWeight: '500',
    color: '#333'
  },
  activityContent: {
    fontSize: '14px',
    color: '#666'
  },
  activityTime: {
    fontSize: '12px',
    color: '#999',
    marginTop: '4px'
  },
  footer: {
    padding: '15px 24px',
    backgroundColor: '#fff',
    borderTop: '1px solid #eee',
    fontSize: '13px',
    color: '#999',
    textAlign: 'center'
  }
}

const HomePage = () => {
  const [user, setUser] = useState<{ username: string } | null>(null)
  const [activeNav, setActiveNav] = useState('dashboard')
  const navigate = useNavigate()
  const location = useLocation()

  // 组件加载时从localStorage获取用户信息
  useEffect(() => {
    const isLoggedIn = localStorage.getItem('isLoggedIn')
    const userStr = localStorage.getItem('user')
    if (!isLoggedIn || !userStr) {
      navigate('/login')
      return
    }
    try {
      const userData = JSON.parse(userStr)
      setUser(userData)
    } catch (error) {
      console.error('解析用户数据出错:', error)
      localStorage.removeItem('isLoggedIn')
      localStorage.removeItem('user')
      navigate('/login')
    }
  }, [navigate])

  // 处理登出
  const handleLogout = () => {
    localStorage.removeItem('isLoggedIn')
    localStorage.removeItem('user')
    navigate('/login')
  }

  // 处理导航点击
  const handleNavClick = (id: string) => {
    console.log(`导航到: ${id}`)
    setActiveNav(id)
    
    // 根据导航ID进行路由跳转
    switch(id) {
      case 'online-ordering':
        navigate('/OnlineOrdering');
        break;
      case 'Box':
        navigate('/Box');
        break;
      case 'OnlineBoxes':
        navigate('/homepage/onlineboxes');
        break;
      default:
        // 其他导航项的处理逻辑可以在这里添加
        break;
    }
    if (id === 'outbound') {
      navigate('/homepage/iamview');
    } else {
      // 其它导航逻辑
    }
    // 实际项目中在这里处理导航逻辑
    if (id === 'ShowPendingShipmentWaybills') {
      navigate('/Layout/ShowPendingShipmentWaybills');
    }
    if (id === 'product-management') {
      navigate('/ProductManage')
    }
    // 实际项目中在这里处理其他导航逻辑
  }


  
  // 处理快速访问项点击
  const handleQuickAccessClick = (id: string) => {
    // 实际项目中在这里处理不同功能的跳转
    alert(`快速访问: ${id}`)
  }

  if (!user) return null // 用户信息加载前不渲染

  // 判断是否为首页（/homepage 或 /homepage/）
  const isHome = location.pathname === '/homepage' || location.pathname === '/homepage/'

  return (
    <div style={style.pageContainer}>
      {/* 头部导航 */}
      <header style={style.header}>
        <div style={style.headerLeft}>
          <div style={style.logo}>WMS系统</div>
        </div>
        <div style={style.headerRight}>
          <div style={style.userInfo}>
            <span>👤 {user.username}</span>
          </div>
          <button onClick={handleLogout} style={style.logoutButton}>
            退出登录
          </button>
        </div>
      </header>

      {/* 主内容区 */}
      <div style={style.mainContent}>
        {/* 侧边导航 */}
        <aside style={style.sidebar}>
          {navItems.map(item => (
            <div
              key={item.id}
              style={{ ...style.navItem, ...(activeNav === item.id ? style.activeNavItem : {}) }}
              onClick={() => handleNavClick(item.id)}
            >
              {item.label}
            </div>
          ))}
        </aside>

        {/* 内容区 */}
        <main style={style.content}>
          {isHome ? (
            <>
              {/* 仪表盘卡片 */}
              <div style={style.dashboardCard}>
                <div style={style.card}>
                  <div style={style.cardHeader}>
                    <div style={style.cardTitle}>总库存量</div>
                    <div style={style.cardValue}>{mockStats.totalInventory}</div>
                  </div>
                </div>
                <div style={style.card}>
                  <div style={style.cardHeader}>
                    <div style={style.cardTitle}>待处理订单</div>
                    <div style={style.cardValue}>{mockStats.pendingOrders}</div>
                  </div>
                </div>
                <div style={style.card}>
                  <div style={style.cardHeader}>
                    <div style={style.cardTitle}>低库存商品</div>
                    <div style={style.cardValue}>{mockStats.lowStockItems}</div>
                  </div>
                </div>
                <div style={style.card}>
                  <div style={style.cardHeader}>
                    <div style={style.cardTitle}>本月销售额</div>
                    <div style={style.cardValue}>¥{mockStats.monthlySales.toLocaleString()}</div>
                  </div>
                </div>
              </div>

              {/* 快速访问 */}
              <section style={style.quickAccessSection}>
                <h2>快速访问</h2>
                <div style={style.quickAccessGrid}>
                  {quickAccessItems.map(item => (
                    <div
                      key={item.id}
                      style={style.quickAccessItem}
                      onClick={() => handleQuickAccessClick(item.id)}
                    >
                      <div style={style.quickAccessIcon}>{item.icon}</div>
                      <div style={style.quickAccessText}>{item.label}</div>
                    </div>
                  ))}
                </div>
              </section>

              {/* 最近活动 */}
              <section style={style.recentActivity}>
                <h2>最近活动</h2>
                {mockActivities.map(activity => (
                  <div key={activity.id} style={style.activityItem}>
                    <div style={style.activityTitle}>{activity.title}</div>
                    <div style={style.activityContent}>{activity.content}</div>
                    <div style={style.activityTime}>{activity.time}</div>
                  </div>
                ))}
              </section>
            </>
          ) : (
            <Outlet />
          )}
        </main>
      </div>

      {/* 页脚 */}
      <footer style={style.footer}>
        © 2024 WMS仓库管理系统 - 版本 1.0.0
      </footer>
    </div>
  )
}

export default HomePage
